package kalender.backend;

import java.util.Properties;
import java.sql.*;
import java.io.*;


public class DatabaseManager {
	private static Connection connection = null;
	
	public static Connection getConnection() {
		if (connection == null) {
			connection = getNewConnection();
		}
		return connection;
	}
	
	private static Connection getNewConnection() {
		try {
			File file = new File("conf/DatabaseConfig.xml");
			FileInputStream fis = new FileInputStream(file);
		
			Properties prop1 = new Properties();
			prop1.loadFromXML(fis);
			
			Connection conn = DriverManager.getConnection(prop1.getProperty("url"), prop1);
			return conn;
		} catch (IOException e) {
			System.err.println("FATAL ERROR: Could not read config file DatabaseConfig.xml: " + e);
			e.printStackTrace();
			System.exit(1);
		} catch (SQLException e) {
			printException(e);
			System.exit(1);
		}
		return null;
	}
	
	/* Taken from serafim's lecture */
	public static void printWarning(SQLWarning warning) {
		if (warning != null) {
			System.out.println("\n--Warning--");
			while (warning != null) {
				System.out.println("Message: " + warning.getMessage());
				System.out.println("SQLState: " + warning.getSQLState());
				System.out.print("Vendor error code: ");
				System.out.println(warning.getErrorCode());
				System.out.println("");
				warning = warning.getNextWarning();
			}
		}
	}
	
	public static void printException(SQLException e) {
		System.out.println("\n--Exception--");
		System.out.println("Message: " + e.getMessage());
		System.out.println("SQLState: " + e.getSQLState());
		System.out.print("Vendor error code: ");
		System.out.println(e.getErrorCode());
		e.printStackTrace();
	}
	
	public static void createTable(int num) throws BackendException {
		Connection conn = DatabaseManager.getConnection();
		try {
			Statement stm = conn.createStatement();
			stm.executeUpdate("CREATE TABLE test" + num + " (id INT)");
		} catch (SQLException e) {
			DatabaseManager.printException(e);
			throw new BackendException("Databasfel. Var god försök igen.", e);			
		}
	}
}
